package cn.iocoder.yudao.module.system.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class WeChatWorkAppNotifier {

    private static final String CORP_ID = "wwc6bd5711da0ea17b ";
    private static final String SECRET = "KjF-xfExt2TZlhXUu8DuSuv7535rrikjvkle87MFew8";
    private static final String AGENT_ID = "1000010";

    public static void sendTextMessage(String message) throws IOException {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
        String json = createJson(message);
        sendHttpPost(url, json);
    }

    private static String getAccessToken() throws IOException {
        String  host = "wb.fmc-asia.cn";
        String  api = "/web/WeChatWork_Interface.asmx/TextMsgSend?";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + CORP_ID + "&corpsecret=" + SECRET;
        // 创建URL对象
        URL obj = new URL(url);
        // 打开连接
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // 设置请求方法
        con.setRequestMethod("GET");
        // 连接，从URL获取响应代码
        con.connect();
        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        // 将响应转换为JSON对象进行解析
        JSONObject jsonObject = JSONObject.parseObject(response.toString());
        // 从JSON对象中获取access_token
        return jsonObject.getString("access_token");
    }

    private static String createJson(String content) {
        Map<String, Object> map = new HashMap<>();
        map.put("touser", "@all"); // 可指定成员ID，"@all"表示全体成员
        map.put("msgtype", "text");
        Map<String, String> textMap = new HashMap<>();
        textMap.put("content", content);
        map.put("text", textMap);
        map.put("agentid", AGENT_ID);
        map.put("safe", 0); // 表示消息是否是保密消息，0表示否
        return new Gson().toJson(map);
    }

    private static void sendHttpPost(String url, String json) throws IOException {
        // 尝试创建URL对象
        URL obj = new URL(url);
        // 打开连接
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // 设置请求方法
        con.setRequestMethod("POST");
        // 设置请求头信息
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Charset", "utf-8");
        // 发送POST请求必须设置
        con.setDoOutput(true);

        // 获取输出流并发送请求体
        try(DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            // 写入请求体
            //wr.writeBytes(json);
            wr.flush();
        }

        // 读取响应
        int responseCode = con.getResponseCode();
        System.out.println("POST Response Code :: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) { //成功
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            // 打印结果
            System.out.println(response.toString());
            // 将响应转换为JSON对象（如果需要的话）
            JSONObject jsonResponse = JSONObject.parseObject(response.toString());
            // 这里可以处理响应的JSON数据
        } else { // 失败
            System.out.println("POST request did not work.");
        }
    }

    public static void main(String[] args) {
        try {
            String url = "https://wb.fmc-asia.cn/web/WeChatWork_Interface.asmx?op=TextMsgSend&touser=700385&content=\"测试111\"&agentid=1000011";
            String msg = "";
            sendHttpPost(url,msg);
            //sendTextMessage("这是一条测试消息");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
